package tjs.study.notes.dotest.redis.locker.redission;

import org.redisson.api.RedissonClient;
import tjs.study.notes.dotest.zookper.locker.common.RLock;
import tjs.study.notes.dotest.zookper.locker.common.RLockFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by Nicky.Tang on 2021/11/9 8:53 下午
 *
 * @since 02.12.10
 */
public class RLockRedissionFactory implements RLockFactory {
    private RedissonClient lockClient;

    public RLockRedissionFactory(RedissonClient zkClient) {
        this.lockClient = zkClient;
    }

    public RLock getLock(String key) {

        org.redisson.api.RLock redisLock = lockClient.getLock(key);
        RLock rLock = new RLock() {
            @Override
            public void close() throws Exception {
                try {
                    redisLock.unlock();
                } catch (IllegalMonitorStateException ex) {
                    if (ex.getMessage() != null && ex.getMessage().indexOf("not locked by current thread") != -1) {
                        System.out.println("not locked by current thread...");
                    } else {
                        throw ex;
                    }
                }
            }

            @Override
            public String getLockPath() {
                return redisLock.getName();
            }

            @Override
            public boolean lock() {
                //redisLock.lock();
                try {
                    return redisLock.tryLock(9999,20, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public void unlock() {
                redisLock.unlock();
            }
        };
        return rLock;
    }


}
